<?php
namespace App\Http\Controllers\Withdraw;

use App\Http\Controllers\Controller;
use App\Libraries\Tools\CheckAuth;
use App\Models\Config\Config;
use App\Models\MLM\MLMBalance;
use App\Models\Shop\Shop;
use App\Models\Shop\ShopWithdrawApply;
use App\Models\Shop\ShopWithdrawConfig;
use App\Models\User\User;
use App\Models\User\UserPwLock;
use App\Models\User\UserWithdrawApply;
use App\Models\User\UserWithdrawConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class WithdrawController extends Controller{



    public function __construct(){

    }

    /**
     * 商家提现申请
     * @param Request $request
     * @param ShopWithdrawApply $shopWithdrawApply
     * @return \Illuminate\Http\JsonResponse
     */
    public function addShopApply(Request $request, ShopWithdrawApply $shopWithdrawApply){
        $validator = Validator::make($request->all(), [
            'shop_id' => 'required|integer',
            'apply_amount' => 'required|numeric',
        ], [
            'shop_id.required' => '10001',
            'shop_id.integer' => '10002',
            'apply_amount.required' => '10001',
            'apply_amount.numeric' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        if(!CheckAuth::checkIfManager($request['shop_id'])){
            return $this->sendFailResponse(400, 40101);
        }

        $shop = Shop::where('shop_id', $request['shop_id'])->where('status', 1)->first();
        if(empty($shop)){
            return $this->sendFailResponse(400, 40400);
        }

        $config = ShopWithdrawConfig::where('shop_id', $request['shop_id'])->first();
        if(empty($config)){
            $config = new \stdClass();
            $config->ratio = Config::where('key', 'shop_withdraw_ratio')->first()->value;
            $config->limit = Config::where('key', 'shop_withdraw_limit')->first()->value;
        }

        if($config->limit > $request['apply_amount'] && !empty($config->limit)){
            return $this->sendFailResponse(400, 40001);
        }

        DB::beginTransaction();
        try{
            $flag = $shop->where('shop_id', $request['shop_id'])
                ->where('balance', '>=', $request['apply_amount'])
                ->decrement('balance', $request['apply_amount']);
            if(empty($flag)){
                DB::rollBack();
                return $this->sendFailResponse(400, 40004);
            }
            $shopWithdrawApply->shop_id = $request['shop_id'];
            $shopWithdrawApply->user_id = Auth::id();
            $shopWithdrawApply->channel = 3;
            $shopWithdrawApply->apply_amount = $request['apply_amount'];
            $shopWithdrawApply->withdraw_amount = sprintf('%.2f', $request['apply_amount'] * (1-$config->ratio));
            $shopWithdrawApply->ratio = $config->ratio;
            $shopWithdrawApply->status = 0;
            $shopWithdrawApply->save();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->sendFailResponse(500, 50000);
        }

        return $this->sendSuccessResponse([]);
    }

    /**
     * 用户提现申请
     * @param Request $request
     * @param UserWithdrawApply $userWithdrawApply
     * @return \Illuminate\Http\JsonResponse
     */
    public function addUserApply(Request $request, UserWithdrawApply $userWithdrawApply){
        $validator = Validator::make($request->all(), [
            'password' => 'required|string|size:6',
            'apply_amount' => 'required|numeric',
            'type' => 'required|in:1,2',//1-余额 2-MLM
            'acc' => 'required|string',
            'acc_name' => 'required|string',
        ], [
            'password.required' => '10001',
            'password.string' => '10002',
            'password.size' => '10002',
            'apply_amount.required' => '10001',
            'apply_amount.numeric' => '10002',
            'type.required' => '10001',
            'type.in' => '10002',
            'acc.required' => '10001',
            'acc.string' => '10002',
            'acc_name.required' => '10001',
            'acc_name.string' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        $err_code[] = CheckAuth::checkPaymentPw(Auth::user(), $request['password']);
        $err_code[] = CheckAuth::checkWithdrawLevel(Auth::user(), 2);//2级才能提现
        foreach($err_code as $v){
            if($v != 200){
                return $this->sendFailResponse(400, $v);
            }
        }

        $config = UserWithdrawConfig::where('user_id', Auth::id())->first();
        if(empty($config)){
            $config = new \stdClass();
            if($request['type'] == 1){
                $config->ratio = Config::where('key', 'user_withdraw_ratio')->first()->value;
                $config->limit = Config::where('key', 'user_withdraw_limit')->first()->value;
            }else{
                $config->mlm_ratio = Config::where('key', 'mlm_withdraw_ratio')->first()->value;
                $config->mlm_limit = Config::where('key', 'mlm_withdraw_limit')->first()->value;
            }
        }

        if($request['type'] == 1){
            $ratio = $config->ratio;
            $limit = $config->limit;
        }else{
            $ratio = $config->mlm_ratio;
            $limit = $config->mlm_limit;
        }

        if($limit > $request['apply_amount'] && !empty($limit)){
            return $this->sendFailResponse(400, 40001);
        }

        DB::beginTransaction();
        try{
            if($request['type'] == 1){
                $flag = User::where('user_id', Auth::id())
                    ->where('balance', '>=', $request['apply_amount'])
                    ->decrement('balance', $request['apply_amount']);
            }else{
                $flag = MLMBalance::where('user_id', Auth::id())
                    ->where('balance', '>=', $request['apply_amount'])
                    ->decrement('balance', $request['apply_amount']);
            }
            if(empty($flag)){
                DB::rollBack();
                return $this->sendFailResponse(400, 40004);
            }
            $userWithdrawApply->user_id = Auth::id();
            $userWithdrawApply->type = $request['type'];
            $userWithdrawApply->channel = 1;
            $userWithdrawApply->apply_amount = $request['apply_amount'];
            $userWithdrawApply->withdraw_amount = sprintf('%.2f', $request['apply_amount'] * (1-$ratio));
            $userWithdrawApply->ratio = $ratio;
            $userWithdrawApply->status = 0;
            $userWithdrawApply->acc = $request['acc'];
            $userWithdrawApply->acc_name = $request['acc_name'];
            $userWithdrawApply->save();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return $this->sendFailResponse(500, 50000);
        }

        return $this->sendSuccessResponse([]);
    }
}